from datetime import datetime
from pydantic import BaseModel
from typing import Optional
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func

from app.db.database import Base


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    openid = Column(String(100), unique=True, index=True)
    nickname = Column(String(50))
    avatar_url = Column(String(255))
    phone = Column(String(20))
    location = Column(String(255))
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 关联关系
    lost_items = relationship("Item", back_populates="owner", foreign_keys="Item.owner_id")
    found_items = relationship("Item", back_populates="finder", foreign_keys="Item.finder_id")
    claims = relationship("Claim", back_populates="user")

    def __repr__(self):
        return f"<User(id={self.id}, nickname={self.nickname})>"


class UserInfo(BaseModel):
    """用户信息"""
    id: int
    nickName: Optional[str] = None
    avatarUrl: Optional[str] = None
    created_at: Optional[datetime] = None

    class Config:
        orm_mode = True


class WechatLoginResponse(BaseModel):
    """登录响应"""
    code: int
    message: str
    data: dict


class UserInfoRequest(BaseModel):
    nickName: str
    avatarUrl: str


class UserUpdateRequest(BaseModel):
    """更新用户信息请求"""
    nickName: Optional[str] = None


class UserResponse(BaseModel):
    id: int
    nickName: Optional[str] = None
    avatarUrl: Optional[str] = None
    created_at: datetime

    class Config:
        orm_mode = True